package com.tianqu.tms.www.car.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.dto.MemberRentalLocationInfo;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.entity.RentalContractInfo;
import com.tianqu.tms.www.car.actionform.CarPendingLiftActionForm;
import com.tianqu.tms.www.car.viewhelper.CarPendingLiftViewHelper;

/**
 * @author mufeiyu
 * 高级管理 - 信息查看 controller
 */
public class CarSeniorManagementConfirmController extends TmsController {
	private Logger logger = Logger.getLogger(CarSeniorManagementConfirmController.class);

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();		
		
		// 添加事务提交异常捕获
		try {
			controller.begin();
			CarPendingLiftViewHelper viewhelper = new CarPendingLiftViewHelper();
			CarPendingLiftActionForm form = (CarPendingLiftActionForm)uc.getInputForm();
			String memberId = form.getMemId();
			if(!"1".equals((String)uc.getAttribute("modifyFlag"))){
				memberId = (String)uc.getAttribute("id");
			}
			Member member = Member.getInstance();
			member=member.findMemberInfoByMemId(memberId);
			
			viewhelper = setDetailInfo(member,viewhelper);
			
			// 已登记库存数量
			int registedCount = member.findRegistedCount(memberId);
			viewhelper.setRegistedCount(registedCount);
			
			//
			MemberRentalLocationInfo memberRentalLocationInfo = member.findMemberRentalLocationInfoCount(member.getBusinessNo());
			String unusedAnnualTransactionVolume = memberRentalLocationInfo.getUnusedAnnualTransactionVolume();
			String unusedCarPort = memberRentalLocationInfo.getUnusedCarPort();
			viewhelper.setUnusedAnnualTransactionVolume(StringUtil.getPointBetweenThree(StringUtils.isNotBlank(unusedAnnualTransactionVolume)?Integer.parseInt(unusedAnnualTransactionVolume):0));
			viewhelper.setUnusedCarPort(StringUtil.getPointBetweenThree(StringUtils.isNotBlank(unusedCarPort)?Integer.parseInt(unusedCarPort):0));
			
			// 空余登记库存数量
			if (StringUtil.isNullOrBlank(viewhelper.getAnnualTransactionVolume())) {
				viewhelper.setNoRegistedCount(0);
			} else {
				viewhelper.setNoRegistedCount(StringUtil.getint(viewhelper.getAnnualTransactionVolume().replace(",", "")) - registedCount);
			}

			uc.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			
			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");
	}

	/**
	 * view赋值
	 * @return
	 */
	private CarPendingLiftViewHelper setDetailInfo(Member member,CarPendingLiftViewHelper viewhelper) throws TmsDaoException{
		Codes code = Codes.getInstance();
		
		//商户编号
		viewhelper.setMemId(String.valueOf(member.getMemId()));
		//商户名称
		viewhelper.setMemName(member.getShortName());
		//商户状态
		if(member.getMemStatus()== 1){
			viewhelper.setMemStatus("正常");
		}else if(member.getMemStatus()== 2){
			viewhelper.setMemStatus("删除");
		}else if(member.getMemStatus()== 3){
			viewhelper.setMemStatus("禁用");
		}else{
			viewhelper.setMemStatus("");
		}
		viewhelper.setContractType(member.getContractType());
		if(member.getContractType()== 1){
			viewhelper.setContractTypeStr("已签约");
		}else if(member.getContractType()== 2){
			viewhelper.setContractTypeStr("未签约");
		}else{
			viewhelper.setMemStatus("");
		}
		
		viewhelper.setContractTime(member.getContractTime());
		//注册时间
		viewhelper.setInsertTime(member.getInsertTime());
		//允许库存停放数量
		viewhelper.setCarPortStr(StringUtil.getPointBetweenThree(member.getCarPort()));
		//允许库存登记数量
		viewhelper.setAnnualTransactionVolume(StringUtil.getPointBetweenThree(member.getAnnualTransactionVolume()));
		//易碎贴免费数量
		viewhelper.setFragileStickerFreePort(StringUtil.getPointBetweenThree(member.getFragileStickerFreePort()));	
		//车源推荐权重
		viewhelper.setRecommend(code.getItemValueByItemIdAndItemCode(Codes.RECOMMEND_TYPE, Integer.valueOf(member.getRecommend())));
		//合同编号
		String businessNo = member.getBusinessNo();
		//长期有效识别道闸
		viewhelper.setIdentityRangeStr(convertIdentityRangeStr(member.getIdentityRange()));
		//临时有效识别道闸
		viewhelper.setTmpIdentityRangeStr(convertIdentityRangeStr(member.getTmpIdentityRange()));
		
		viewhelper.setUsedCarPort(member.getUsedCarPort());
		viewhelper.setFreeCarPort(member.getFreeCarPort());

		viewhelper.setBusinessNo(businessNo);
		List<RentalContractInfo> rentalList = new ArrayList<RentalContractInfo>(); 
		if(!StringUtil.isNullOrBlank(businessNo)){
			String[] list= businessNo.split(",");
			List<String> serialList = Arrays.asList(list);
			RentalContractInfo contractInfo = RentalContractInfo.getInstance();
			
			for(int i=0;i<serialList.size();i++){
				contractInfo = contractInfo.findContractInfoBySerial(serialList.get(i));
				contractInfo.setNum(i+1);
				if(i%2 == 0){
					contractInfo.setCssFlag(1);
				}else {
					contractInfo.setCssFlag(2);
				}
				rentalList.add(contractInfo);
			}
		}
		//关联租位信息
		viewhelper.setRentalLocationInfoList(rentalList);
		
		return viewhelper;
	}
	
	private String convertIdentityRangeStr(String identityRangeCode) throws TmsDaoException{
		if (StringUtil.isNullOrBlank(identityRangeCode)) return "";
		Codes code = Codes.getInstance();
		String r = "";
		String[] tmp = identityRangeCode.split(",");
		for (int i = 0; i < tmp.length; i++){
			int itemCode = StringUtils.isNumeric(tmp[i])?Integer.parseInt(tmp[i]):-1;
			if(i!=0) r += ",";
			r += code.getItemValueByItemIdAndItemCode(Codes.GATEWAY_TYPE, itemCode);
		}
		return r;
	}
}
